package org.snia.server.processor;

import java.io.File;

import org.snia.cdmi.Constants;
import org.snia.cdmi.model.MetaDataObject;
import org.snia.util.JuuidUtils;
import org.snia.util.SerializeUtil;

public class MetaDataObjectXMLProcessor implements MetaProcessor {


	@Override
	public void deleteMetadata(String uuid) {
		String uuidpath = JuuidUtils.getuuidPath(uuid);
		String dir = Constants.MATA_DATAOBJECT_ROOT + File.separator + uuidpath;
		String filepath = dir + File.separator + uuid + ".xml";
		File file = new File(filepath);
		if (file.exists()) {
			file.delete();
		}

		// TODO 删除父空目录
		System.out.println("删除对象的元数据文件时，元数据文件的父目录地址： " + file.getParent());
		File parent = new File(file.getParent());
	}

	@Override
	public void createMetadata(String uuid, Object meta) {
		String uuidpath = JuuidUtils.getuuidPath(uuid);
		String dir = Constants.MATA_DATAOBJECT_ROOT + File.separator + uuidpath;
		File folder = new File(dir);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		
		String filepath = dir + File.separator + uuid + ".xml";
		// 序列化为XML文件
		SerializeUtil.serializeToXml(meta, filepath);
	}

	@Override
	public void updateMetadata(String uuid, Object meta) {
		String uuidpath = JuuidUtils.getuuidPath(uuid);
		String dir = Constants.MATA_DATAOBJECT_ROOT + File.separator + uuidpath;
		File folder = new File(dir);
		if (!folder.exists()) {
			//抛出异常
		}
		
		String filepath = dir + File.separator + uuid + ".xml";
		// 序列化为XML文件
		SerializeUtil.serializeToXml(meta, filepath);

	}

	@Override
	public Object getMetadata(String uuid) {
		// 获得容器对象的UUID
		String uuidpath = JuuidUtils.getuuidPath(uuid);
		// 获得元数据文件的实际存储位置
		String dir = Constants.MATA_DATAOBJECT_ROOT + File.separator + uuidpath;
		String filepath = dir + File.separator + uuid + ".xml";
		// 反序列化得到容器的元数据对象
		File file = new File(filepath);
		if (file.exists()) {
			//如果同时有操作，可能存在异常
			return (MetaDataObject) SerializeUtil.deSerializeFromXml(filepath);
		}
		return null;
	}

	@Override
	public boolean exist(String uuid) {
		String uuidpath = JuuidUtils.getuuidPath(uuid);
		String dir = Constants.MATA_DATAOBJECT_ROOT + File.separator + uuidpath;
		String filepath = dir + File.separator + uuid + ".xml";
		File file = new File(filepath);
		return file.exists();
	}

}
